"""
核心配置文件
"""
import os
from typing import Optional, List
from pydantic import BaseSettings, validator
from pydantic.types import SecretStr


class Settings(BaseSettings):
    """应用配置类"""
    
    # 基础配置
    PROJECT_NAME: str = "SaaS平台发布与回滚系统"
    VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"
    
    # 安全配置
    SECRET_KEY: SecretStr = SecretStr("your-secret-key-change-in-production")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8  # 8 days
    
    # 数据库配置
    DATABASE_URL: str = "postgresql://user:password@localhost/saas_deploy"
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    REDIS_DB: int = 0
    
    # Celery配置
    CELERY_BROKER_URL: str = "redis://localhost:6379/1"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/2"
    
    # 环境配置
    ENVIRONMENT: str = "development"
    DEBUG: bool = True
    LOG_LEVEL: str = "INFO"
    
    # 跨域配置
    BACKEND_CORS_ORIGINS: List[str] = ["http://localhost:3000", "http://localhost:8080"]
    
    # 文件存储配置
    UPLOAD_DIR: str = "uploads"
    MAX_FILE_SIZE: int = 100 * 1024 * 1024  # 100MB
    
    # 发布配置
    DEPLOYMENT_TIMEOUT: int = 1800  # 30分钟
    HEALTH_CHECK_INTERVAL: int = 30  # 30秒
    ROLLBACK_TIMEOUT: int = 600  # 10分钟
    
    # 监控配置
    METRICS_ENABLED: bool = True
    ALERT_EMAIL: Optional[str] = None
    ALERT_WEBHOOK: Optional[str] = None
    
    # 容器配置
    DOCKER_REGISTRY: str = "localhost:5000"
    KUBERNETES_NAMESPACE: str = "saas-deploy"
    
    # 备份配置
    BACKUP_ENABLED: bool = True
    BACKUP_RETENTION_DAYS: int = 30
    BACKUP_SCHEDULE: str = "0 2 * * *"  # 每天凌晨2点
    
    @validator("BACKEND_CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v):
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)
    
    @validator("DATABASE_URL", pre=True)
    def validate_database_url(cls, v):
        if not v:
            raise ValueError("DATABASE_URL不能为空")
        return v
    
    class Config:
        env_file = ".env"
        case_sensitive = True


# 创建全局配置实例
settings = Settings()


# 环境相关配置
class DevelopmentSettings(Settings):
    """开发环境配置"""
    DEBUG: bool = True
    LOG_LEVEL: str = "DEBUG"


class ProductionSettings(Settings):
    """生产环境配置"""
    DEBUG: bool = False
    LOG_LEVEL: str = "WARNING"
    
    @validator("SECRET_KEY")
    def validate_secret_key(cls, v):
        if v.get_secret_value() == "your-secret-key-change-in-production":
            raise ValueError("生产环境必须设置安全的SECRET_KEY")
        return v


class TestingSettings(Settings):
    """测试环境配置"""
    DEBUG: bool = True
    DATABASE_URL: str = "postgresql://test:test@localhost/test_saas_deploy"
    REDIS_URL: str = "redis://localhost:6379/15"


# 根据环境获取配置
def get_settings() -> Settings:
    """根据环境获取配置"""
    env = os.getenv("ENVIRONMENT", "development")
    
    if env == "production":
        return ProductionSettings()
    elif env == "testing":
        return TestingSettings()
    else:
        return DevelopmentSettings()


# 导出配置实例
current_settings = get_settings()
